import 'package:flutter/material.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_message_mention_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/tweet/tweet_content.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'message_content.dart';

///消息
class MessageList extends StatefulWidget {
  final bool isAtMe;

  const MessageList({Key key, this.isAtMe}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new MessageListState(isAtMe);
  }
}

class MessageListState extends State<MessageList> with AutomaticKeepAliveClientMixin<MessageList> {
  final bool isAtMe;
  MessageListState(this.isAtMe);

  HttpRepository httpRepository;
  int size = 0;
  bool isLoadedData = false;
  bool deletable = false;

  int requestCount;
  int totalResults;
  int responseCount;
  String pageToken;

  double paddingParentHorizontal = Dimens.gap_activity_horizontal;
  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscMessageMentionEntity> list;

  RefreshController controller = RefreshController(initialRefresh: true);


  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          if (size == 0) {
            return NoDataWidget();
          } else {
            return buildListItem(index);
          }
        },
        separatorBuilder: (BuildContext context, int index) {
          return SmallWidgets.buildLineBigger();
        },
        itemCount: isLoadedData && size == 0? 1 : size,
      ),
    );
  }

  buildListItem(int index){
    OscMessageMentionEntity item = list.elementAt(index);
    final GlobalKey<TweetContentState> anchorKey = GlobalKey<TweetContentState>();
    return GestureDetector(
      onTap: (){
        double height = anchorKey.currentContext.size.height;
//        jump2PageForResult(TweetDetail(tweet: item, expandedHeight: height,));
      },
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.all(paddingParentHorizontal),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            OscPortraitWidget(id: item.author.id, portraitImageUrl: item.author.portrait,),
            MessageContent(item: item, key: anchorKey,),
          ],
        ),
      ),
    );
  }




  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    await httpRepository.getUserMassages(isAtMe: isAtMe, pageToken: pageToken).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult<OscMessageMentionEntity> result = resp.result;
        if(result != null){
          List<OscMessageMentionEntity> tempItems = result.items;
          responseCount = result.responseCount;
          requestCount = result.requestCount;
          if(StringUtil.isEmpty(pageToken)){
            list = tempItems;
          } else {
            list.addAll(tempItems);
          }
          pageToken = result.nextPageToken;
          size = list?.length??0;
          if(responseCount < requestCount || size == result.totalResults){
            controller.loadNoData();
          } else {
            controller.loadComplete();
          }
        }
      }
    });
    if(mounted){
      setState(() {
        controller.refreshCompleted();
      });
    }
  }

  deleteTweet(int id, int index) async{
    await httpRepository.deleteTweet(id).then((resp){
      if(resp.success){
        list.removeAt(index);
        if(mounted){
          setState(() {

          });
        }
      } else {
        showTips(resp.message);
      }
    });
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
